/**
 * @description order controller
 * @author boen
 */

const Order = require('../models/Order')
const { getAddressById } = require('./address')
const { getProductList } = require('./product')

/**
 * 创建订单
 * @param {string} username 用户名
 * @param {Object} data 数据 
 * @returns 
 */
async function createOrder(username,data) {
    const { addressId, products } = data
    // 获取收货地址详情信息
    const addressInfo = await getAddressById(addressId)
    // 获取商品列表id
    const productsId = products.map(item => item.id)
    // 获取商品列表信息
    const productList = await getProductList(data.shopId, productsId)
    // 整合购买量和商品信息
    const newProducts = productList.map( product => {
        const productId = product._id.toString()
        // 使用id获取对应的购买量
        const orderSales = products.find( item => item.id === productId).num
        if(!orderSales) {
            throw Error('未找到匹配的销量数据')
        }
        return {
            product,
            orderSales
        }
    })
    // 整合订单信息
    const orderInfo = {
        username,
        shopId: data.shopId,
        shopName: data.shopName,
        isCanceled: data.isCanceled || false,
        address: addressInfo,
        products: newProducts
    }
    const newOrder = await Order.create(orderInfo)
    return newOrder
}

module.exports = {
    createOrder
}